<template>
  <div class="container">
    <!-- 固定导航 -->
    <van-nav-bar fixed left-arrow @click-left="$router.back()">
      <template #title>{{ user ? user.username : "wait" }}</template>
    </van-nav-bar>

    <!-- 聊天主体区域 -->
    <van-pull-refresh
      v-model="loading"
      success-text="刷新成功"
      @refresh="initChatHistory"
      :disabled="finished"
      class="chat-list"
    >
      <div v-for="item in list" :key="item.id">
        <!-- 左侧是机器人小思 -->
        <div class="chat-item left" v-if="item.sender == user.username">
          <van-image fit="cover" round :src="user.decorate_avatar" />
          <div class="chat-pao">{{ item.message }}</div>
        </div>

        <!-- 右侧是当前用户 -->
        <div class="chat-item right" v-else>
          <div class="chat-pao">{{ item.message }}</div>
          <van-image fit="cover" round :src="profile.decorate_avatar" />
        </div>
      </div>
    </van-pull-refresh>
    <!-- 对话区域 -->
    <div class="reply-container van-hairline--top">
      <van-field v-model.trim="word" placeholder="说点什么...">
        <template #button>
          <span @click.enter="send()" style="font-size: 12px; color: #999"
            >发送</span
          >
        </template>
      </van-field>
    </div>
  </div>
</template>

<script>
import { mapState } from "vuex";
import { chatHistoryAPI, profileAPI } from "@/api/userApi";
export default {
  name: "Chat",
  props: ["id"],
  computed: {
    ...mapState("user", ["tokenInfo", "profile"]),
    ...mapState("chat", ["socket", "newMsg"]),
  },
  data() {
    return {
      // 用户输入的聊天内容
      word: "",
      list: [
        // 1. 只根据 name 属性，即可判断出这个消息应该渲染到左侧还是右侧
        // { name: 'xs', msg: 'hi，你好！我是小思1' },
        // { name: 'me', msg: '我是编程小王子1' }
      ],
      user: null,
      loading: false,
      isLoading: false,
      finished: false,
      page: 1,
    };
  },
  methods: {
    async initChatHistory() {
      const { data: res } = await chatHistoryAPI(this.id, this.page);
      this.list = [...res.results.reverse(), ...this.list];
      this.loading = false;
      if (!res.next) {
        this.finished = true;
      }
      this.page++;
    },
    async initUser() {
      const { data: res } = await profileAPI(this.id);
      this.user = res;
    },
    // 提交按钮的点击事件处理函数
    send() {
      if (!this.word) return;
      const message = {
        type: "chat.message",
        receiver_id: this.id,
        message: this.word,
      };

      this.socket.send(JSON.stringify(message));
      this.word = "";
    },
    scrollToBottom() {
      const aChatItem = document.querySelectorAll(".chat-item");
      let lastChat = aChatItem[aChatItem.length - 1];
      lastChat.scrollIntoView({
        behavior: "smooth",
        block: "end",
      });
    },
  },
  watch: {
    newMsg() {
      if (this.newMsg.is_system) {
        return;
      }
      this.list.push(this.newMsg);
      this.$nextTick(() => {
        this.scrollToBottom();
      });
    },
  },
  beforeRouteEnter(to, from, next) {
    next((vm) => {
      // 通过 `vm` 访问组件实例
      if (vm.tokenInfo.user_id == Number(to.params.id)) {
        vm.$router.back();
      }
    });
  },
  created() {
    this.initUser();
    this.initChatHistory();
  },
  updated() {
    if (this.page == 2 && this.list.length >= 10) {
      this.$nextTick(() => {
        this.scrollToBottom();
      });
    }
  },
};
</script>

<style lang="less" scoped>
.container {
  height: 100%;
  width: 100%;
  position: absolute;
  left: 0;
  top: 0;
  box-sizing: border-box;
  background: #fafafa;
  padding: 46px 0 50px 0;
  .chat-list {
    height: 100%;
    overflow-y: scroll;
    .chat-item {
      padding: 10px;
      .van-image {
        vertical-align: top;
        width: 40px;
        height: 40px;
      }
      .chat-pao {
        vertical-align: top;
        display: inline-block;
        min-width: 40px;
        max-width: 70%;
        min-height: 40px;
        line-height: 38px;
        border: 0.5px solid #c2d9ea;
        border-radius: 4px;
        position: relative;
        padding: 0 10px;
        background-color: #e0effb;
        word-break: break-all;
        font-size: 14px;
        color: #333;
        &::before {
          content: "";
          width: 10px;
          height: 10px;
          position: absolute;
          top: 12px;
          border-top: 0.5px solid #c2d9ea;
          border-right: 0.5px solid #c2d9ea;
          background: #e0effb;
        }
      }
    }
  }
}
.chat-item.right {
  text-align: right;
  .chat-pao {
    margin-left: 0;
    margin-right: 15px;
    &::before {
      right: -6px;
      transform: rotate(45deg);
    }
  }
}
.chat-item.left {
  text-align: left;
  .chat-pao {
    margin-left: 15px;
    margin-right: 0;
    &::before {
      left: -5px;
      transform: rotate(-135deg);
    }
  }
}
.reply-container {
  position: fixed;
  left: 0;
  bottom: 0;
  height: 44px;
  width: 100%;
  background: #f5f5f5;
  z-index: 9999;
}
</style>
